// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config_api_impl

import (
	"context"

	"gitcode.com/opendragonfly/df_proto_gen_go.git/config_api"
	"gitcode.com/opendragonfly/df_server/config"
	"gitcode.com/opendragonfly/df_server/dao/member_dao"
)

func (apiImpl *ConfigApiImpl) GetDataTtl(ctx context.Context, req *config_api.GetDataTtlRequest) (*config_api.GetDataTtlResponse, error) {
	emptyInfo := &config_api.DataTtlInfo{}

	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	remoteCfg, ok := cfg.GetRemote(req.RemoteId)
	if !ok {
		return &config_api.GetDataTtlResponse{
			Code:    config_api.GetDataTtlResponse_CODE_NO_REMOTE,
			ErrMsg:  "鉴权服务器不存在",
			DataTtl: emptyInfo,
		}, nil
	}
	_, _, err = member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
	if err != nil {
		return &config_api.GetDataTtlResponse{
			Code:    config_api.GetDataTtlResponse_CODE_NO_PERMISSION,
			ErrMsg:  "用户不存在",
			DataTtl: emptyInfo,
		}, nil
	}

	return &config_api.GetDataTtlResponse{
		Code: config_api.GetDataTtlResponse_CODE_OK,
		DataTtl: &config_api.DataTtlInfo{
			KeepTraceDay: uint32(cfg.KeepTraceDay),
		},
	}, nil
}

func (apiImpl *ConfigApiImpl) GetPortInfo(ctx context.Context, req *config_api.GetPortInfoRequest) (*config_api.GetPortInfoResponse, error) {
	emptyInfo := &config_api.PortInfo{}

	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	remoteCfg, ok := cfg.GetRemote(req.RemoteId)
	if !ok {
		return &config_api.GetPortInfoResponse{
			Code:     config_api.GetPortInfoResponse_CODE_NO_REMOTE,
			ErrMsg:   "鉴权服务器不存在",
			PortInfo: emptyInfo,
		}, nil
	}
	_, _, err = member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
	if err != nil {
		return &config_api.GetPortInfoResponse{
			Code:     config_api.GetPortInfoResponse_CODE_NO_PERMISSION,
			ErrMsg:   "用户不存在",
			PortInfo: emptyInfo,
		}, nil
	}
	return &config_api.GetPortInfoResponse{
		Code: config_api.GetPortInfoResponse_CODE_OK,
		PortInfo: &config_api.PortInfo{
			HasZipkinPort:         cfg.Port.EnableZipkin,
			ZipkinPort:            uint32(cfg.Port.ZipkinPort),
			HasJaegerGrpcPort:     cfg.Port.EnableJaegerGrpc,
			JaegerGrpcPort:        uint32(cfg.Port.JaegerGrpcPort),
			HasJaegerHttpPort:     cfg.Port.EnableJaegerHttp,
			JaegerHttpPort:        uint32(cfg.Port.JaegerHttpPort),
			HasSkywalkingGrpcPort: cfg.Port.EnableSkywalkingGrpc,
			SkywalkingGrpcPort:    uint32(cfg.Port.SkywalkingGrpcPort),
			HasSkywalkingHttpPort: cfg.Port.EnableSkywalkingHttp,
			SkywalkingHttpPort:    uint32(cfg.Port.SkywalkingHttpPort),
			HasOtlpGrpcPort:       cfg.Port.EnableOtlpGrpc,
			OtlpGrpcPort:          uint32(cfg.Port.OtlpGrpcPort),
			HasOtlpHttpPort:       cfg.Port.EnableOtlpHttp,
			OtlpHttpPort:          uint32(cfg.Port.OtlpHttpPort),
		},
	}, nil
}
